package service.impl;

import mapper.OrderMapper;
import mapper.ProductMapper;
import model.Order;
import model.Product;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.ProductService;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author : look-word
 * 2022-07-17 10:29
 **/
@Transactional
@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductMapper productMapper;

    @Resource
    private OrderMapper orderMapper;

    @Override
    public void reduceStock(Integer id) throws Exception {
        Product product = productMapper.getProduct(id);
        if (product.getStock() <= 0) {
            throw new RuntimeException("库存不足");
        }
        // 减库存
        int i = productMapper.reduceStock(id);
        if (i == 1) {
            Order order = new Order();
            order.setId(UUID.randomUUID().toString());
            order.setUserid(1);
            order.setPid(id);
            orderMapper.insert(order);
        } else {
            throw new RuntimeException("库存失败");
        }
    }
}
